import adbutils
import uiautomator2 as u2
import wda
import subprocess

from common.app_info import AndroidApp
from common.error import AndroidWifiErr, PhoneNotConnectErr


class MyDriver:

    @staticmethod
    def get_android_devices():
        """
        获取安卓手机的 设备id
        """
        more_android_devices = adbutils.adb.device_list()
        devices_list = [m.serial for m in more_android_devices]
        if devices_list:
            return devices_list
        raise PhoneNotConnectErr('没有找到Android设备，请检查设备是否连上了电脑')

    @staticmethod
    def get_ios_devices(app_tag: str):
        """
        返回 苹果手机的 uuid    MarketName  ProductVersion
        """
        try:
            ios_phone_info = subprocess.check_output('tidevice list', shell=True, encoding='utf8')
        except Exception as e:
            ios_phone_info = subprocess.check_output('tidevice list', shell=True, encoding='gbk')
        get_ios_phone_info = ios_phone_info.split('\n')

        if len(get_ios_phone_info[1]) < 20:
            raise PhoneNotConnectErr('没有找到ios设备，请检查设备是否连上了电脑')
        else:
            check_info = get_ios_phone_info[1].split()
            new_ios_phone_info = {"UDID": check_info[0],
                                  "SerialNumber": check_info[1],
                                  "ProductVersion": check_info[-2],
                                  "ConnType": check_info[-1]}
            try:
                ios_app_info = subprocess.check_output('tidevice applist', shell=True, encoding='gbk')
            except Exception as u:
                ios_app_info = subprocess.check_output('tidevice applist', shell=True, encoding='utf8')

            get_ios_app_info = ios_app_info.split('\n')
            app_list = {"cloudsmart": "云智连", "smart": "360智慧生活", "wx": "微信"}

            get_wda_runner = ""
            get_app_package = ""
            for pi in get_ios_app_info:
                new_pi = pi.split()
                for p in new_pi:
                    if "WebDriverAgentRunner" in p:
                        get_wda_runner = new_pi[0]
                    elif app_list[app_tag] in p:
                        get_app_package = new_pi[0]
                if get_wda_runner != "" and get_app_package != "":
                    break

            return new_ios_phone_info, get_wda_runner, get_app_package

    @staticmethod
    def android_watch_alert(u2_driver):
        """
        如果存在元素则自动点击
        keyword="yes|允许|好的|跳过"
        """
        keyword = "忽略|允许|忽略该设备|确定|跳过"
        with u2_driver.watch_context(autostart=False) as wct:
            # ctx.when("^立即(下载|更新)").when("取消").click()  # 当同时出现 （立即安装 或 立即取消）和 取消 按钮的时候，点击取消
            for c in keyword.split('|'):
                wct.when(c).click()
        wct.start()
        return wct

    def init_android_driver(self, app_tag="smart"):
        """
        wifi 连接参考  https://zhidao.baidu.com/question/2019709811778593508.html
        """
        try:
            print('app_tag', app_tag)
            u2Driver = u2.connect()
            app_package = AndroidApp[app_tag.lower()]["appPackage"]
            print('app_package', app_package)
            u2Driver.app_start(package_name=app_package, wait=True, use_monkey=True)
            u2Driver.settings['wait_timeout'] = 10
            print('u2Driver', u2Driver)

            return u2Driver, app_package
        except Exception as e:
            print('eeeeeeee????', e)

    def init_ios_driver(self, app_tag="Smart"):
        app_tag_info = app_tag.lower()
        ios_device_info, ios_wda, ios_package = self.get_ios_devices(app_tag_info)
        _udId = ios_device_info['UDID']
        print(f"连接到苹果测试手机：{ios_device_info['SerialNumber']}，版本：{ios_device_info['ProductVersion']}")
        wda_client = wda.USBClient(udid=_udId, port=8100)
        print("启动测试app")
        wda_client.app_start(bundle_id=ios_package, wait_for_quiescence=True)
        wda_client.implicitly_wait(10)  # 设置隐式等待
        return wda_client, ios_package
